package myApp::Controller::Places;

use strict;
use warnings;
use Agente;
use base 'Catalyst::Controller';

=head1 NAME

myApp::Controller::Places - Catalyst Controller

=head1 DESCRIPTION

Catalyst Controller.

=head1 METHODS

=cut


=head2 index 

=cut

sub index : Private {
    my ( $self, $c ) = @_;

    $c->response->body('Matched myApp::Controller::Places in Places.');
}


sub list : Local {
        # Retrieve the usual perl OO '$self' for this object. $c is the Catalyst
        # 'Context' that's used to 'glue together' the various components
        # that make up the application
        my ($self, $c) = @_;
    	
        # Retrieve all of the book records as book model objects and store in the
        # stash where they can be accessed by the TT template
        $c->stash->{places} = [$c->model('myAppDB::Places')->all];
        
        # Set the TT template to use.  You will almost always want to do this
        # in your action methods (action methods respond to user input in
        # your controllers).
	$DB::single = 1;
        $c->stash->{template} = 'places/list.tt2';
    }
sub infos : Local {

	my ($self, $c, $id) = @_;

	$c->stash->{places} = [$c->model('myAppDB::Places')->search({id => $id})];
	$c->stash->{wikis} = [$c->model('myAppDB::Wiki')->search({places => $id})];
	$c->stash->{links} = [$c->model('myAppDB::Enlaces')->search({places => $id})];
	$c->stash->{weathers} = [$c->model('myAppDB::Weather')->search({places => $id})];
	$c->stash->{template} = 'places/info.tt2';
}
sub busqueda : Local {
	
	my ($self, $c) = @_;
	my $id;
	my $busqueda = $c->request->params->{ search }     || 'N/A';
	my %wiki = Agente::search_wiki ( $busqueda );
	#my %weather = Agente::buscar_weather ( $busqueda, $wiki{prov});

#Se inserta el lugar primero
	my $place = $c->model('myAppDB::Places')->search_rs({lugar => $busqueda});
	if (defined ($place)) { #Se hará una actualización
		$place->update ({
				lugar=> $busqueda,
				demas=> $wiki{prov} });
		$id = $place;
		
	} else { # Se crea el elemento
		my $rs = $c->model('myAppDB::Places')->create ({
			lugar=>$busqueda,
			demas=>$wiki{prov}
		});
		$id = $rs->id;
		print "Creando\n";
	}

	#print $id;

	$c->forward('list');
	
}
=head1 AUTHOR

Raúl Sánchez Ruiz

=head1 LICENSE

This library is free software, you can redistribute it and/or modify
it under the same terms as Perl itself.

=cut

1;
